#include "alarmdashboard.h"
#include "AlarmItemWidget.h"
#include <QGlobalStatic>
#include <QScrollBar>
#include <QAction>
#include <QTimer>
#include "parsecandata.h"
#include "alarmqueue.h"

Q_GLOBAL_STATIC(AlarmDashboard,m_instance)

AlarmDashboard::AlarmDashboard(QWidget *parent)
    : QScrollArea(parent)
{
    setWidgetResizable(true);
    setupContainer();

    this->setStyleSheet("background-color:#0D0D0D;border:1px solid #0D0D0D;");

    connect(ParseCANDataIns,&ParseCANData::addAlarm,this,&AlarmDashboard::on_addAlarm);

    // 初始化滚动动画
    m_scrollAnimation = new QPropertyAnimation(verticalScrollBar(), "value", this);
    m_scrollAnimation->setDuration(500);  // 500ms动画时长
    m_scrollAnimation->setEasingCurve(QEasingCurve::OutQuad);

    //初始化报警对象池
    for(int i= 0; i < m_maxVisibleItems * 2; i++)
    {
        AlarmItemWidget *item = nullptr;
        item = new AlarmItemWidget(this);
        m_itemPool.push_back(item);
    }

    //添加菜单
    QStringList anctionNames;
    anctionNames << "清除";
    this->setContextMenuPolicy(Qt::ActionsContextMenu);

    foreach (QString anctionName, anctionNames) {
        QAction *action = new QAction(anctionName, this);
        connect(action, SIGNAL(triggered(bool)), this, SLOT(clearMessage()));
        this->addAction(action);
    }
}

AlarmDashboard *AlarmDashboard::Instance()
{
    return m_instance;
}

void AlarmDashboard::setupContainer()
{
    m_container = new QWidget(this);
    m_layout = new QVBoxLayout(m_container);
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->setSpacing(5);
    setWidget(m_container);
}

void AlarmDashboard::on_addAlarm(const AlarmData &data)
{
    show();
    // 对象池管理
//    if(m_itemPool.size() > m_maxVisibleItems * 2 && !m_itemPool.isEmpty()) {
//        item = m_itemPool.takeFirst();  //takeFirst()会返回并删除第一个
//    } else {
//        item = new AlarmItemWidget(this);
//        m_itemPool.push_back(item);
//    }
    if(m_itemPool.isEmpty()) {
        return;
    }

    AlarmItemWidget *item = nullptr;
    if(m_item_cuurentIndex >= m_itemPool.count()) {
        m_item_cuurentIndex = 0;
    }
    item = m_itemPool.at(m_item_cuurentIndex);
    m_item_cuurentIndex += 1;

    QMetaObject::invokeMethod(this, [=]{
        item->updateContent(data);
        m_layout->addWidget(item);       
    }, Qt::QueuedConnection);

    // 改用立即执行的异步滚动（100ms延迟）减少cpu负担
    QTimer::singleShot(100, this, [this]{
        if(m_autoScrollEnabled) {
            performSmoothScroll();
        }
    });
}

void AlarmDashboard::clearMessage()
{
    hide();
}

void AlarmDashboard::performSmoothScroll()
{
    const int endValue = verticalScrollBar()->maximum();
    if(m_scrollAnimation->state() == QPropertyAnimation::Running) {
        m_scrollAnimation->stop();
    }

    m_scrollAnimation->setStartValue(verticalScrollBar()->value());
    m_scrollAnimation->setEndValue(endValue);
    m_scrollAnimation->start();
}

// 新增手动滚动控制
void AlarmDashboard::setAutoScrollEnabled(bool enable)
{
    m_autoScrollEnabled = enable;
    if(enable) performSmoothScroll();
}

void AlarmDashboard::wheelEvent(QWheelEvent *event)
{
    // 当用户手动滚动时暂停自动滚动
    m_autoScrollEnabled = false;
    QScrollArea::wheelEvent(event);

    // 2秒后恢复自动滚动（如果到底部）
    QTimer::singleShot(2000, this, [this]{
        if(verticalScrollBar()->value() == verticalScrollBar()->maximum()) {
            m_autoScrollEnabled = true;
        }
    });
}
